//
//  BORefreshControl.swift
//  VVbo
//
//  Created by Mr.Run on 2017/9/4.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

import UIKit

private let refreshOffset:CGFloat = 126

enum RefreshState {
    case Normal
    case Pulling
    case WillRefresh
}

class BORefreshControl: UIControl {
    
    private weak var scrollView: UIScrollView?
    fileprivate lazy var refreshView:RefreshView = RefreshView.refreshView()
    
    override init(frame: CGRect) {
        super.init(frame: CGRect())
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        
        super.willMove(toWindow: newSuperview as? UIWindow)
        
        
        guard let sv = newSuperview as? UIScrollView else {
            return
        }
        
        scrollView = sv
        
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        
        guard let sv = scrollView else {
            return
        }
        
        let height = -(sv.contentInset.top + sv.contentOffset.y)
        
        if height < 0 {
            return
        }
        
        self.frame = CGRect(x: 0, y: -height, width: sv.bounds.size.width, height: height)
        
        if refreshView.refreshState != .WillRefresh{
            refreshView.parentViewHeight = height
        }
        
        
        if sv.isDragging {
            if height > refreshOffset && (refreshView.refreshState == .Normal) {
                print("放手刷新")
                refreshView.refreshState = .Pulling
            }else if height <= refreshOffset && (refreshView.refreshState == .Pulling) {
                print("继续劲拉...")
                refreshView.refreshState = .Normal
            }
        }else{
            if refreshView.refreshState == .Pulling {
                print("准备刷新...")
//                refreshView.refreshState = .WillRefresh
//                var inset = sv.contentInset
//                inset.top += refreshOffset
//                sv.contentInset = inset
                beginRefreshing()
                sendActions(for: .valueChanged)
            }
        }
        
    }
    
    override func removeFromSuperview() {
        
        superview?.removeObserver(self, forKeyPath: "contentOffset")
        
        super.removeFromSuperview()
    }
    
    func beginRefreshing() {
        print("begin refresh")
        
        guard let sv = scrollView else {
            return
        }
        
        if refreshView.refreshState == .WillRefresh {
            return
        }
        refreshView.refreshState = .WillRefresh
        var inset = sv.contentInset
        inset.top += refreshOffset
        sv.contentInset = inset
        refreshView.refreshState = .WillRefresh
        refreshView.parentViewHeight = refreshOffset
    }

    func endRefreshing() {
        print("end refresh")
        
        guard let sv = scrollView else {
            return
        }
        if refreshView.refreshState != .WillRefresh {
            return
        }
        refreshView.refreshState = .Normal
        var inset = sv.contentInset
        inset.top -= refreshOffset
        sv.contentInset = inset
    }
    
}

extension BORefreshControl {
    fileprivate func setupUI() {
//        clipsToBounds = true
        backgroundColor = superview?.backgroundColor
        addSubview(refreshView)
        
        refreshView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshView.bounds.width))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshView.bounds.height))
        
    }
}
